require "fileaction"
require "file_manager"


class RequestsController < ApplicationController
  helper_method :getlink
  before_filter :require_session

  def new
    @request = Request.new()
     
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @article }
    end
  end   

  def create
    if params[:request][:file] == ""
      flash[:error] = 'Please choose a file to upload!'
      respond_to do |format|
        format.html {redirect_to :back || '/'}
        format.xml  {head :ok}
      end
      return true;
    end    
    
    @request = Request.create(params[:request])
    @request.session_id = session[:id]
    @request.save
    
    respond_to do |format|
      flash[:notice] = "file successfully uploaded"

      format.html {redirect_to request_path(@request)}
      format.xml  {head :ok}
    end
  end  
  
  def show    
    @request = Request.find(params[:id])

    if @request.session_id != session[:id]
      flash[:error] = 'This session has expired.'
      redirect_to '/'
      return
    end

    @children = Request.find_all_by_from_id(@request.id)
    @menus = Menu.find_roots(@request)
    
    @files = get_session_files
    
    if params[:a]
      menu = Menu.find_by_url(params[:a])
      if not menu 
        redirect_to request_path(@request)
        return
      end

      newfile,msg = FileManager.execute(@request, menu) 
      #todo: exception handle
      respond_to do |format|
        format.html {redirect_to request_path(newfile)}
      end
      flash[:notice] = msg
    end  
  end
  
  def index
    @files = get_session_files
    @menus = []# Menu.find_roots(nil)   

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @requests }
    end
  end
  
  def getlink(id)
    @request = Request.find(id)
    if @request
      @request.getlink
    else
      '/404.html'
    end
  end
  
  def get_thumbnail(id)
    @request = Request.find(id)
    if @request
      @request.get_thumbnail
    else
      '/images/default.jpg'
    end
  end

  private 
    def require_session      
      if session[:id] == nil       
        session[:id] = Session.create.id
      end
      true
    end

    def get_session_files
      return Request.find_all_by_from_id(nil,:conditions=> ["session_id = ?",session[:id]], :order => "updated_at DESC" )
    end
end
